import axios from 'axios'
import store from './store.js'
import Utils from './utils.js'


const appConfig = { //应用配置
  baseUrl: '/api',
  version: '1.0'
}
appConfig.baseUrl = Utils.config().apiHost

axios.defaults.baseURL = appConfig.baseUrl  //请求接口地址
axios.defaults.validateStatus = function (status) {
  return status < 500
}
axios.defaults.timeout = 10000

const ajaxInfo = {
  url: '',
  method: 'get',
  status: 0
}

//添加一个请求拦截器
axios.interceptors.request.use(function (config) {
  //在请求发出之前进行一些操作
  
  ajaxInfo.url = config.url
  ajaxInfo.method = config.method.toLowerCase()
  console.log('请求前', config.url)
  for (let key in config.params) {
    // alert(config.params[key])
    if (config.params[key] === null || config.params[key] === '') {
      if (config.params[key] !== 0) delete config.params[key]
    }
  }
  return config
}, function (err) {
  //Do something with request error
  return Promise.reject(error);
})

axios.interceptors.response.use(function (res) {
  console.log('请求后', res.config.url)
  console.log('请求ajax', ajaxInfo.url)
  ajaxInfo.url = res.config.url
  console.warn(res)
  if (ajaxInfo.url.indexOf('shareInfo') > -1 || ajaxInfo.url.indexOf('leaflet/addLeafletRecord') > -1 || ajaxInfo.url.indexOf('leaflet/actRecord') > -1){
    //分享接口
    return res.data
  }
  if (res.data.code === 200 ){
    return res.data
  }else{
    let errMsg = res.data.errorMsg 
    store.commit('toast', errMsg)
    return Promise.reject(res)
  }
  
},function (err) {
  store.commit('toast', '前方人山人海，请您稍后再试~')
  return Promise.reject(err);
})

export default axios